<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\controller\BaseController;
use think\exception\ValidateException;

class Login extends BaseController
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['login', 'logout'];

    public function initialize()
    {
        parent::initialize();

    }

    public function login()
    {

        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            $data = [
                'username' => $username,
                'password' => $password,
            ];
            $validate = [
                'username' => 'require|length:3,30',
                'password' => 'require|length:6,30',
            ];
            $messge = [
                'username.require' => '请输入用户名',
                'username.length' => '用户名至少三位',
                'password.require' => '请输入密码',
                'password.length' => '密码至少六位',
            ];
            try {
                $this->validate($data, $validate, $messge);
                $validateRes = true;
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $validateRes = $e->getError();
            }
            if ($validateRes !== true) {
                return $this->error($validateRes);
            }
            $result = $this->auth->login($username, $password);
            if ($result === true) {
                $userInfo = [
                    'userId' => $this->auth->id,
                    'username' => $this->auth->username,
                    'realName' => $this->auth->realname,
                    'token' => $this->auth->getToken(),
                    'desc' => '',
                    'roles' => [],
                ];
                return $this->success(lang('Login successful'), $userInfo);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : lang('Username or password is incorrect');
                return $this->error($msg);
            }
        }
    }

    public function logout()
    {
        if ($this->request->isPost()) {
            $this->auth->logout();
            return $this->success(lang('Logout successful'));
        }
    }
}